<template>
  <div class="currencyExchange">
    <div class="currencyExchangeCont">
      <div class="currencyTitle center">{{ $t('exchange.crossConv') }}</div>
      <div class="back">
        <div class="flexb mb">
          <span class="usedCaption">{{ $t('exchange.use') }}</span>
          <span class="colorThis" @click="exchangeRecordVisible=true;">{{ $t('exchange.exchangeRecord') }}</span>
        </div>
        <div class="mb15">
          <div class="chainbox">
            <el-select v-model="value"
            @change="handleChangeValue" class="nodeSelect">
              <div class="flexc iconImg" slot="prefix">
                <img :src="checkedValue.icon"/>
                <span style="padding-left: 50px;">({{checkedValue.chain}} {{ $t('bosChain.chain') }})</span>
              </div>
              <template v-for="item in options">
                <el-option
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  class="listClass">
                  <div class="iconImg">
                    <img :src="item.icon"/>
                    <span>{{ item.label }}</span>
                    <span class="chain">({{item.chain}} {{ $t('bosChain.chain') }})</span>
                  </div>
                </el-option>
              </template>
            </el-select>
          </div>
        </div>
        <div class="flexb exchangeCapition mb5">
          <span class="usedCaption">{{ $t('exchange.conversion') }}</span>
          <span>1{{value}}=1{{conversionBi.value}}</span>
          <i class="iconfont icon-huaban23" @click="handleChangeWay"></i>
        </div>
        <div class="chainbox listClass conversion">
          <div class="iconImg">
            <img :src="conversionBi.icon"/>
            <span>{{conversionBi.value}}</span>
            <span class="chain">({{conversionBi.chain}} {{ $t('bosChain.chain') }})</span>
          </div>
        </div>
      </div>
      <template v-if="way === 1">
        <div>
          <div class="flexb mb5 numberBalance">
            <span>{{ $t('exchange.exchangeQuantity') }}</span>
            <span @click="exchangeNumber=balance" style="cursor: pointer;">{{ $t('myWallet.balance') }}：{{balance}} {{checkedValue.value}}</span>
          </div>
          <div class="mb15 exchangeNum">
            <el-input v-model="exchangeNumber" @blur="handleDecimal" type="number" :placeholder="$t('newpos.pleaseEnterQuantity')"
            :step="0.00000001" :min="0.00000001"
            clearable />
          </div>
        </div>
      </template>
      <template>
        <div>
          <div class="receiveAdd mb5">
            <span>{{conversionBi.value}}</span>
            <span v-if="way === 1">{{ $t('exchange.receivingAddress1') }}</span>
            <span v-else-if="way === 2">{{ $t('newpos.receiveAccount') }}</span>
            <span>（{{conversionBi.chain}} {{ $t('bosChain.chain') }}）</span>
          </div>
          <div class="receivingAccount flex">
            <el-input v-model="address"
            :disabled="way===2"
            :placeholder="$t('exchange.addressOfReceiving', {value: conversionBi.value, chain: conversionBi.chain} )"
            clearable />
          </div>
        </div>
      </template>
      <el-button
        v-loading="loading"
        class="mrbtn flexc"
        type="primary"
        @click="handleSubmit">
        {{ $t('exchange.exchange') }}
      </el-button>
      <!-- <el-button
        v-if="way===2 && !addressforway2"
        v-loading="loading"
        class="mrbtn flexc"
        type="primary"
        @click="handleGetAddress">
        {{loading ? '获取中...' : '获取接收地址'}}
      </el-button> -->
      <div class="right mt15" style="color: #999;">
        *{{ $t('exchange.paidByThemselves') }}
      </div>
    </div>
    <!-- 币种兑换弹窗 EOS链换其他链的币-->
    <el-dialog
      class="confirmDialog"
      :visible.sync="eosToOtherVisible"
      width="400px"
      append-to-body>
      <div class="confirmDialogCont">
        <div class="title center">{{ $t('cpuNet.comfirm') }}</div>
        <div class="backBlue">
          <div class="confirmList">
            <div class="side">{{ $t('exchange.use') }}</div>
            <div class="confirmItem flex">
              <img :src="checkedValue.icon" alt="" class="iconImg">
              <span>{{exchangeNumber}} {{checkedValue.value}}</span>
              <span class="color999">（{{checkedValue.chain}} {{ $t('bosChain.chain') }}）</span>
            </div>
          </div>
          <div class="iconChange">
            <i class="iconfont icon-huaban22"></i>
          </div>
          <!-- 兑换成 -->
          <div class="confirmList">
            <div class="side">{{ $t('exchange.conversion') }}</div>
            <div v-if="checkedValue.conversionBi" class="confirmItem flex">
              <img :src="checkedValue.conversionBi.icon" alt="" class="iconImg">
              <span>{{exchangeNumber}} {{checkedValue.conversionBi.value}}</span>
              <span class="color999">（{{checkedValue.conversionBi.chain}} {{ $t('bosChain.chain') }}）</span>
            </div>
          </div>
        </div>
        <!-- 接收地址 -->
        <div class="confirmList confirmUsed">
          <div class="side mb">{{checkedValue.conversionBi.value}}{{ $t('exchange.receivingAddress1') }}</div>
          <div>{{address}}</div>
        </div>
        <div class="btn flexb">
          <el-button plain @click="eosToOtherVisible = false;">{{ $t('public.cancel') }}</el-button>
          <el-button type="primary" v-loading="loading" @click="handleConfirm">{{ $t('public.sure') }}</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 币种兑换弹窗 其他链币换EOS链的币-->
    <el-dialog
      class="confirmDialog"
      :visible.sync="otherToEosVisible"
      width="540px"
      append-to-body>
      <!-- 订单成交详情 -->
      <div class="otherToEos">
        <div class="title center">{{ $t('exchange.plsTransfer', { value: checkedValue.value, coin: 'BTC' }) }}</div>
        <div class="title center mt5" style="color: #999;">1{{checkedValue.value}}=1{{conversionBi.value}}</div>
        <div class="erweima" v-loading="loadingCode">
          <canvas id="qrcode"></canvas>
        </div>
        <div class="center otherType">{{checkedValue.address}}</div>
        <div class="copyUrl flexc">
          <el-button
            type="primary"
            v-clipboard:copy="checkedValue.address"
            v-clipboard:success="onCopy"
            v-clipboard:error="onError">
            {{ $t('exchange.copyAddress') }}
          </el-button>
        </div>
        <div class="otherTip">
          <p style="color: #333; margin-bottom: 5px; font-size: 14px;">{{ $t('exchange.plsEos', {value: conversionBi.value}) }}</p>
          <p>{{ $t('exchange.exchangeUsdtTip1', {value: checkedValue.value}) }}</p>
          <p v-if="checkedValue.value === 'USDT'">{{ $t('exchange.exchangeUsdtTip2') }}</p>
          <p v-if="checkedValue.value === 'BTC'">{{ $t('exchange.exchangeBtcTip2') }}</p>
          <p>{{ $t('exchange.exchangeUsdtTip3') }}</p>
        </div>
      </div>
    </el-dialog>
    <!-- 兑换记录 -->
    <el-dialog
      class="confirmDialog"
      :title="this.$t('exchange.exchangeRecord')"
      center
      :visible.sync="exchangeRecordVisible"
      width="1020px"
      append-to-body>
      <exchange-record
      :exchangeRecordVisible="exchangeRecordVisible"
      :options="options"/>
    </el-dialog>
  </div>
</template>

<script>

import { bitModel } from '@/utils/eos/bitpeicurrex'; // 兑换记录
import { toFixed, QRcodeCode } from '@/utils/validate';
import ExchangeRecord from '@/views/myWallet/components/ExchangeRecord'; // 兑换记录

export default {
  name: 'currencyExchange', // 币种兑换
  data() {
    return {
      loading: false,
      loadingCode: false,
      address: '',
      addressforway1: '',
      addressforway2: '',
      exchangeNumber: '', // 兑换成数量
      options: [],
      way: 1, // 1 eos链兑换btc链  2 btc链兑换eos链
      value: 'EBTC',
      checkedValue: {
        conversionBi: {},
      },
      conversionBi: {},
      account: '', // 接收地址
      eosToOtherVisible: false, // EOS链换其他链的币弹窗
      otherToEosVisible: false, // 其他链币换EOS链的币弹窗
      exchangeRecordVisible: false, // 兑换记录
      addressList: [], // eos兑换btc中的 eos币种地址列表
      queryAddressTimer: null,
      balance: 0,
      hasgetAddress: false,
    }
  },
  components: {
    ExchangeRecord
  },
  props: {
    currencyExchangeVisible: {
      type: Boolean,
      default: false,
    },
    convert: String,
  },
  watch: {
    currencyExchangeVisible: function change(val) {
      if (val) {
        this.mountedData();
        this.handleChangeValue();
      }
    },
  },
  computed: {},
  created() {},
  mounted() {
    this.mountedData();
    // 选择兑换币
    this.handleChangeValue();
  },
  beforeDestroy() {
    if (this.queryAddressTimer) {
      clearTimeout(this.queryAddressTimer);
    }
  },
  methods: {
    // 确认兑换
    handleConfirm() {
      const params = {
        quantity: `${toFixed(this.exchangeNumber, 8)} ${this.value}`,
        remarks: this.address,
      }
      this.loading = true;
      bitModel.transaction(params, (res) => {
        this.loading = false;
        if (res && res.broadcast) {
          this.$emit('listenCurrencyExchange');
          this.eosToOtherVisible = false;
          return
        }
        bitModel.handleScatterErrorBack(res)
      })
    },
    // 开始兑换
    handleSubmit() {
      if (this.way === 1) {
        if (this.checkedValue.value === 'EUSD' && this.exchangeNumber < 20) {
          this.$message.error(`${this.$t('exchange.exchangeAmountNeeds')} >=20 EUSD`);
          return;
        }
        if (this.checkedValue.value === 'EBTC' && this.exchangeNumber < 0.001) {
          this.$message.error(`${this.$t('exchange.exchangeAmountNeeds')} >= 0.001 EBTC`);
          return;
        }
        if (!this.address) {
          this.$message.error(this.$t('exchange.enterInputReceiveAddress'));
          return;
        }
        this.eosToOtherVisible = true;
      }
      if (this.way === 2) {
        if (!this.conversionBi.address) {
          this.hasgetAddress = false;
          this.handleGetAddress();
          return;
        }
        this.otherToEosVisible = true;
        this.$nextTick(() => {
          this.handleGetCode();
        })
      }
    },
    // 生成兑换二维码
    handleGetCode() {
      this.loadingCode = true;
      const canvas = document.getElementById('qrcode');
      if (canvas) {
        const params = this.checkedValue.address;
        QRcodeCode(params, canvas, 200, (err) => {
          if (err) {
            this.$message.error(this.$t('jy.codeError'));
            return;
          }
          this.loadingCode = false;
        })
      }
    },
    // 获取接收地址
    handleGetAddress() {
      const params = {
        symbol: this.conversionBi.value
      }
      this.loading = true;
      bitModel.eosNewaddress(params, (res) => {
        // console.log(res);
        if (res && res.broadcast) {
          this.$alert(this.$t('exchange.addressHasBeen'), this.$t('public.reTip'), {
            confirmButtonText: this.$t('public.sure')
          });
          this.hasgetAddress = true;
          this.handleQueryAddress();
          return
        }
        this.loading = false;
        bitModel.handleScatterErrorBack(res)
      });
    },

    // 查表获取地址
    handleQueryAddress() {
      const fid = this.addressList.find(v => v.symbol === this.conversionBi.value);
      if (fid || this.way === 1) {
        this.handleChangeValue();
        return;
      }
      bitModel.addressQuery((res) => {
        if (this.queryAddressTimer) {
          clearTimeout(this.queryAddressTimer);
        }
        this.queryAddressTimer = setTimeout(() => {
          this.handleQueryAddress();
        }, 3000);
        if (res && res.rows && res.rows.length > 0) {
          this.addressList = res.rows;
          this.options.forEach((vv) => {
            const v = vv;
            const symbol = this.addressList.find(f => f.symbol === v.conversionBi.value);
            if (symbol && symbol.address) {
              v.conversionBi.id = symbol.id;
              v.conversionBi.address = symbol.address;
            }
          })
          const findaddress = this.options.find(op => op.conversionBi.value === this.conversionBi.value);
          if (findaddress && findaddress.conversionBi.address) {
            this.handleChangeValue();
          }
          if (this.hasgetAddress) {
            this.hasgetAddress = false;
            this.handleSubmit();
          }
        }
      })
    },
    // 改变兑换对象
    handleChangeValue() {
      const item = this.options.find(v => v.value === this.value) || {};
      this.checkedValue = item;
      this.conversionBi = item.conversionBi;
      const fid = this.addressList.find(v => v.symbol === this.conversionBi.value);
      if (!fid && this.way === 2) {
        this.handleQueryAddress();
      }
      if (fid && this.way === 2) {
        const symbol = this.options.find(v => v.conversionBi.value === this.conversionBi.value);
        if (symbol) {
          symbol.id = fid.id;
          symbol.address = fid.address;
          this.conversionBi.id = fid.id;
          this.conversionBi.address = fid.address;
        }
      }
      if (this.way === 1) {
        this.address = this.addressforway1;
        this.handleGetBalance(this.value);
      }
      if (this.way === 2) {
        this.addressforway2 = this.$store.state.app.scatter.identity.accounts[0].name;
        this.address = this.addressforway2;
        if (this.address) {
          this.loading = false;
        }
      }
    },
    // 交换兑换对象
    handleChangeWay() {
      this.way = this.way === 1 ? 2 : 1;
      const conversionBiList = this.options.map(v => v.conversionBi);
      this.options.forEach((vv) => {
        const v = vv;
        const newBi = {};
        newBi.value = v.value;
        newBi.label = v.label;
        newBi.icon = v.icon;
        newBi.chain = v.chain;
        newBi.way = v.way;
        newBi.id = v.id;
        newBi.address = v.address;
        v.conversionBi = newBi;
        const biItem = conversionBiList.find(b => b.way === v.way);
        v.value = biItem.value
        v.label = biItem.label
        v.icon = biItem.icon
        v.chain = biItem.chain
        v.id = biItem.id;
        v.address = biItem.address;
      });
      this.value = this.conversionBi.value;
      this.handleChangeValue();
    },
    // 格式化小数位
    handleDecimal() {
      this.exchangeNumber = toFixed(this.exchangeNumber, 8);
    },
    // 获取对像余额
    handleGetBalance(symbol) {
      bitModel.getBitBalance(symbol, 'bitpietokens', (res) => {
        if (res && res.length > 0) {
          this.balance = toFixed(parseFloat(res[0], 0), 8);
          return
        }
        this.balance = toFixed(0, 8);
      })
    },
    onCopy() {
      this.$message.success(this.$t('myWallet.copySuccess'));
    },
    onError() {
      this.$message.error(this.$t('myWallet.copyError'));
    },
    mountedData() {
      this.way = 1;
      this.options = [
        {
          value: 'EBTC',
          label: 'EBTC',
          icon: 'https://ndi.340wan.com/eos/bitpietokens-ebtc.png',
          chain: 'EOS',
          address: '',
          id: '',
          way: 1,
          conversionBi: {
            value: 'BTC',
            label: 'BTC',
            icon: 'https://ndi.340wan.com/upload/20190725/d5757dd9d73f4b78994799ef7e53df90.png',
            chain: 'BTC',
            address: '',
            id: '',
            way: 1
          }
        },
        {
          value: 'EUSD',
          label: 'EUSD',
          icon: 'https://ndi.340wan.com/eos/bitpietokens-eusd.png',
          chain: 'EOS',
          address: '',
          id: '',
          way: 2,
          conversionBi: {
            value: 'USDT',
            label: 'USDT',
            icon: 'https://ndi.340wan.com/upload/20190725/1b3aa8830f584448a1a2f8cb2b717adc.png',
            chain: 'BTC',
            address: '',
            id: '',
            way: 2
          }
        },
      ];
      this.address = '';
      this.addressforway1 = '';
      this.addressforway2 = '';
      this.exchangeNumber = ''; // 兑换成数量
      this.hasgetAddress = false;
      this.confirmDialogVisible = false;
      this.value = this.convert;
      this.address = this.addressforway1;
      bitModel.scatterInit(this, () => {});
      // this.handleGetBalance(this.value);
    },
  },
}
</script>
<style lang="scss" scoped>
.currencyExchangeCont {
  padding: 10px 0;

  .colorThis {
    cursor: pointer;
  }

  .currencyTitle {
    font-size: 18px;
    margin-top: -45px;
    margin-bottom: 40px;
  }

  .back {
    padding: 10px 20px 20px;
    background: rgba(233, 242, 255, .58);
    margin-bottom: 20px;
  }

  .usedCaption {
    color: #278EDA;
  }

  .chainbox {
    .nodeSelect {
      width: 100%;
    }

    .iconImg {
      padding-left: 10px;
      height: 40px;
      img {
        display: inline-block;
        width: 25px;
      }
    }
    /deep/ .el-input__inner {
      padding-left: 45px;
    }
  }

  .exchangeCapition {
    position: relative;
    margin-top: 40px;

    i {
      position: absolute;
      left: 50%;
      top: -130%;
      transform: translate(-50%, 0);
      font-size: 18px;
      cursor: pointer;
      border-radius: 50%;
      color: #4A90E2;
      border: 1px solid #4A90E2;
      background: #fff;
      padding: 5px 6px;
    }

    span:nth-child(2) {
      color: #999;
    }
  }

  .numberBalance {
    padding: 0 20px;
    color: #999;
  }

  .exchangeNum {
    padding: 0 20px;
  }

  .receivingAccount {
    padding: 0 20px;

    span {
      margin-right: 32px;
    }

    /deep/ .el-input {
      width: 100%;
    }
  }

  .mrbtn {
    width: 100%;
    margin: 30px auto 0;
  }

  .receiveAdd {
    padding: 0 20px;

    span:nth-child(3) {
      font-size: 12px;
      color: #999;
    }
  }
}
.listClass {
  padding-left: 15px;
  .iconImg {
    height: 40px;
    img {
      display: inline-block;
      width: 25px;
      vertical-align: middle;
      margin-top: -4px;
    }

    .chain {
      margin-left: 5px;
      // color: #999;
    }
  }
}

.conversion {
  width: 100%;
  line-height: 40px;
  border-radius: 5px;
  border: 1px solid #dcdfe6;

  .iconImg {
    padding-left: 0 !important;
  }
}

.confirmDialogCont {
  padding: 0 20px 30px 20px;

  .title {
    font-size: 18px;
    color: #278EDA;
    margin-bottom: 30px;
  }

  .backBlue {
    padding: 20px 28px;
    background: rgba(233, 242, 255, .58);
    margin-bottom: 20px;
    border-radius: 5px;

    .iconImg {
      display: inline-block;
      width: 25px;
      vertical-align: middle;
    }
  }

  .confirmList {
    div:nth-child(1) {
      color: #999;
    }

    div:nth-child(2) {
    }

    .confirmItem {
      line-height: 36px;

      img {
        margin-right: 5px;
      }
    }

    .color999 {
      color: #999;
      font-size: 12px;
    }
  }

  .iconChange {
    text-align: center;
    padding: 10px 0;

    i {
      font-size: 16px;
      color: #278EDA;
      border-radius: 50%;
      border: 1px solid #4A90E2;
      background: #fff;
      padding: 5px;
    }
  }

  .confirmUsed {
    margin-bottom: 20px;
  }

  .btn {
    // padding: 0 70px;
    .el-button {
      width: 150px;
    }
  }
}

.otherToEos {
  .erweima {
    width: 200px;
    height: 200px;
    margin: 10px auto;
    background: skyblue;
  }

  .otherType {
    // padding: 5px 110px;

    span:nth-child(1) {
      color: #999;
    }
  }
  .copyUrl {
    margin-top: 10px;
    padding-bottom: 20px;
    border-bottom: 1px solid #BBBBBB;

    span {
      padding: 5px;
      background: #ECECEC;
      cursor: pointer;
    }
  }

  .otherTip {
    padding: 20px 25px 0;
    color: #999;
    font-size: 12px;
    p {
      margin-bottom: 5px;
    }
  }
}
.confirmDialog {
  /deep/ .el-dialog__header {
    padding-top: 30px;
  }
}

.theme-1B1D27 {
  .conversion {
    color: RGBA(197, 206, 228, 1);
    border: 1px solid #4e5b85;
    background: #152247;
  }

  .back, .backBlue {
    background-color: rgb(33, 42, 63);
  }

  .exchangeCapition {
    i {
      background: rgb(33, 42, 63) !important;
    }
  }
}
</style>

